package com.lglbc.day18.config;

import com.lglbc.day18.dao.UserMapper;
import com.lglbc.day18.entity.Role;
import com.lglbc.day18.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        User user = userMapper.queryUserByUsername(username);
        List<Role> roles = userMapper.getRolesByUserId(user.getId());
        user.setRoles(roles);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("user not found");
        }
        return user;
    }
}
